package com.dynamic.mybatis.core.generator.helper;

import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.dynamic.mybatis.core.generator.InjectorHelper;
import com.dynamic.mybatis.core.metadata.MappedStatementField;
import com.dynamic.mybatis.core.metadata.MappedStatementMetaField;
import com.dynamic.mybatis.core.metadata.MappedStatementTable;

import java.util.Optional;

import static java.util.stream.Collectors.joining;

/**
 * @Description
 * @Author xs
 * @Date 2023/4/14 15:35
 */
public class SelectInjectorHelper extends InjectorHelper {


    /**
     * SQL 查询所有表字段
     *
     * @param table        表信息
     * @param queryWrapper 是否为使用 queryWrapper 查询
     * @return sql 脚本
     */
    public static String sqlSelectColumns(MappedStatementTable table, boolean queryWrapper) {
        /* 假设存在用户自定义的 resultMap 映射返回 */
        String selectColumns = ASTERISK;

            /* 未设置 resultMap 或者 resultMap 是自动构建的,视为属于mp的规则范围内 */
            selectColumns = SelectInjectorHelper.getAllSqlSelect(table);

        if (!queryWrapper) {
            return selectColumns;
        }
        return convertChooseEwSelect(selectColumns);
    }


    public static String convertChooseEwSelect(final String otherwise) {
        return SqlScriptUtils.convertChoose(String.format("%s != null and %s != null", WRAPPER, Q_WRAPPER_SQL_SELECT),
                SqlScriptUtils.unSafeParam(Q_WRAPPER_SQL_SELECT), otherwise);
    }


    /**
     * 获取包含主键及字段的 select sql 片段
     *
     * @return sql 片段
     */
    public static String getAllSqlSelect(MappedStatementTable table) {
        return chooseSelect(table);
    }

    /**
     * 获取需要进行查询的 select sql 片段
     * @return sql 片段
     */
    public static String chooseSelect(MappedStatementTable table) {
        String sqlSelect = getKeySqlSelect(table);
        String fieldsSqlSelect = table.getFields().stream()
                .map(f -> SelectInjectorHelper.getSqlSelect(table,f)).collect(joining(COMMA));
        if (StringUtils.isNotBlank(sqlSelect) && StringUtils.isNotBlank(fieldsSqlSelect)) {
            return sqlSelect + COMMA + fieldsSqlSelect;
        } else if (StringUtils.isNotBlank(fieldsSqlSelect)) {
            return fieldsSqlSelect;
        }
        return sqlSelect;
    }


    public static String getSqlSelect(MappedStatementTable table,MappedStatementField field){
        boolean needAs = true;
        if (needAs) {
            // 存在指定转换属性
            String propertyFormat = "%s";
            return field.getColumn() + (AS + String.format(propertyFormat, field.getField()));
        } else if (TableInfoHelper.checkRelated(table.isUnderCamel(), field.getField(), field.getColumn())) {
            return field.getColumn() + (AS + field.getField());
        }
        return field.getColumn();
    }


    /**
     * 获取主键的 select sql 片段
     *
     * @return sql 片段
     */
    public static String getKeySqlSelect(MappedStatementTable table) {
        Optional<MappedStatementMetaField> keyField =  getFirstKeyField(table);
        String sqlSelect;
        if ((keyField =  getFirstKeyField(table)).isPresent()) {
            sqlSelect = keyField.get().getColumn();
            if (keyRelated) {
                sqlSelect += (AS + keyField.get().getField());
            }
        } else {
            sqlSelect = EMPTY;
        }
        return sqlSelect;
    }
}